package com.doubao.controller;

import com.doubao.entity.dto.UserLoginDTO;
import com.doubao.entity.vo.UserVO;
import com.doubao.response.Result;
import com.doubao.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;

@Slf4j
@Validated
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Tag(name = "用户接口", description = "用户登录注册相关接口")
public class UserController {

    private final UserService userService;

    @Operation(summary = "微信登录")
    @PostMapping("/wx/login")
    public Result<UserVO> wxLogin(@RequestBody @Valid UserLoginDTO dto) {
        log.info("微信登录请求，参数：{}", dto);
        UserVO userVO = userService.wxLogin(dto);
        log.info("微信登录成功，用户ID：{}", userVO.getId());
        return Result.success(userVO);
    }

    @Operation(summary = "手机号登录")
    @PostMapping("/phone/login")
    public Result<UserVO> phoneLogin(
            @RequestParam @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
            String phone,
            @RequestParam @NotBlank(message = "验证码不能为空")
            String code) {
        log.info("手机号登录请求，手机号：{}", phone);
        UserVO userVO = userService.phoneLogin(phone, code);
        log.info("手机号登录成功，用户ID：{}", userVO.getId());
        return Result.success(userVO);
    }

    @Operation(summary = "更新用户信息")
    @PutMapping("/info")
    public Result<UserVO> updateInfo(
            @RequestAttribute(name = "userId") Long userId,
            @RequestBody @Valid UserVO userVO) {
        log.info("更新用户信息请求，用户ID：{}，更新信息：{}", userId, userVO);
        userService.updateUserInfo(userId, userVO);
        UserVO updatedUser = userService.getUserInfo(userId);
        log.info("用户信息更新成功，用户ID：{}", userId);
        return Result.success(updatedUser);
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public Result<UserVO> getInfo(@RequestHeader(value = "User-Id") Long userId) {
        log.info("获取用户信息请求，用户ID：{}", userId);
        UserVO userVO = userService.getUserInfo(userId);
        return Result.success(userVO);
    }
}
